import {
  Controller,
  Post,
  UseInterceptors,
  UploadedFile,
  UploadedFiles,
  UseGuards,
  Delete,
  Param,
  BadRequestException,
} from '@nestjs/common';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import { UploadService } from './upload.service';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { Roles } from 'src/common/decorators/roles.decorator';
import { RolesGuard } from 'src/common/guards/roles.guard';
import { fileURLToPath } from 'url';

/**
 * 文件上传控制器
 */
@Controller('upload')
@UseGuards(JwtAuthGuard)
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  /**
   *  上传单个图片
   */

  @Post('image')
  @UseInterceptors(FileInterceptor('file'))
  async uploadImage(@UploadedFile() file: Express.Multer.File) {
    // 验证图片
    this.uploadService.validateImage(file);
    // 上传
    const url = await this.uploadService.uploadFile(file, 'images');
    return {
      code: 200,
      message: '上传成功',
      data: { url },
    };
  }
  /**
   * 上传多个图片
   *
   * 字段名: files
   * 最多10张
   */
  @Post('images')
  @UseInterceptors(FilesInterceptor('files', 10))
  async uploadImages(@UploadedFiles() files: Express.Multer.File[]) {
    if (!files || files.length === 0) {
      throw new BadRequestException('请选择文件');
    }

    // 验证每个图片
    files.forEach((file) => this.uploadService.validateImage(file));

    // 批量上传
    const urls = await this.uploadService.uploadFiles(files, 'images');

    return {
      code: 200,
      message: '上传成功',
      data: { urls },
    };
  }

  /**
   *  上传源码文件
   * 只有管理员可以上传
   *
   */

  @Post('source')
  @UseGuards(RolesGuard)
  @Roles('admin')
  @UseInterceptors(FileInterceptor('file'))
  async uploadSource(@UploadedFile() file: Express.Multer.File) {
    // 验证压缩文件
    this.uploadService.validateArchive(file);
    // 上传到 sources 文件夹
    const url = await this.uploadService.uploadFile(file, 'sources');
    return {
      code: 200,
      message: '上传成功',
      data: { url },
    };
  }
  /**
   * 上传商品封面
   */
  @Post('product-cover')
  @UseGuards(RolesGuard)
  @Roles('admin')
  @UseInterceptors(FileInterceptor('file'))
  async uploadProductCover(@UploadedFile() file: Express.Multer.File) {
    this.uploadService.validateImage(file);
    const url = await this.uploadService.uploadFile(file, 'products/covers');

    return {
      code: 200,
      message: '上传成功',
      data: { url },
    };
  }
}
